
var config = require("../utils/config");
var intf = require("../utils/interface");
const db = require('../db')
const Sequelize = require('sequelize')



const fs = require('fs')
const path = require('path')
const multer = require('@koa/multer');

const {
	Op
} = require("sequelize");
module.exports = function(router) {
	//老黄历页面
	/**
	 * @api {GET} /index/dujitang 毒鸡汤
	 * @apiDescription 毒鸡汤
	 * @apiName 毒鸡汤接口
	 * @apiGroup HOME
	 * @apiSuccess {json} result
	 * @apiSuccessExample {json} Success-Response:
	 *  {
	 * 		"code":200,
	 * 		"data":{
	 *			"data":{"content":"你是我的小苹果，哎呀讨厌！我是说我TM真想削你。","_id":"5fbaa160-75cf-11ed-9725-fdb25c09e850","id":"5fbaa161-75cf-11ed-9725-fdb25c09e850"}
	 *		}
	 *	}
	 *  @apiSuccessExample {json} Error-Response:
	 *  {
	 *      "code" : 1,
	 *      "msg" : '获取失败'
	 *  }
	 * @apiSampleRequest http://localhost:3301/lhl/index/dujitang
	 * @apiVersion 1.0.0
	 * 
	 *
	 */
	
	
	let fileName;
	//	注意新版本需要multer.diskStorage()写成这样使用,和老版本multer()有区别,会导致上传成功后目录没有存储生成上传文件
	let upload = multer.diskStorage({
	  //设置文件的存储位置
	  destination:function(req,file,cb){
	    //每天文件夹
	    let date = new Date()
	    let year = date.getFullYear()
	    let month = date.getMonth()+1
	    let day = date.getDate()
	    let dir = "./public/uploads/uploads" + year + month + day
	
	    //判断目录是否存在
	    if(!fs.existsSync(dir)){
	      fs.mkdirSync(dir,{
	        recursive:true
	      })
	    }
	    cb(null,dir)
	  },
	  filename:function(req,file,cb){
	    //设置文件名称
	    fileName = file.fieldname + '-' + Date.now() + path.extname(file.originalname)
	    cb(null,fileName)
	  }
	})
	
	var uploadFile = multer({ storage: upload });
	
	// 实现图片的上传
	router.post('/upload/img', uploadFile.single('myfile'), async ctx => {
	    let path = ctx.request.file.path
		let date = new Date()
		let year = date.getFullYear()
		let month = date.getMonth()+1
		let day = date.getDate()
		let dir = "./public/uploads/uploads" + year + month + day
		//判断目录是否存在
		    if(!fs.existsSync(dir)){
		      fs.mkdirSync(dir,{
		        recursive:true
		      })
		    }
	    path = path.replace(/public/, '/lhl');
		 // path = ctx.request.origin + '' + path.replace(/public/, '/lhl');
		path = path .replace("\\\\", "\/\/");
		path	 = path .replace("\\", "\/");
		path = path .replace("\\", "\/");
		path = path .replace("\\", "\/");
	    // ctx.body = {
	    //     data: path,
	    //     code: 1,
	    //     msg: "文件上传成功"
	    // }
		ctx.rest({msg:'文件上传成功',flle:path})
	});
	// router.get('/index/dujitang', async (ctx) => {
	// 	// var {
	// 	// 	date
	// 	// } = ctx.query;

	// 	//先调用接口查询
	// 	var data1 = {
	// 		key: config.tianKey[0]
	// 	}
	// 	var res1 = await intf.get_interface(config.tianUrl[0] + 'dujitang/index', data1);
	// 	//查到了 查询数据库是否存在，不存在存入数据库
	// 	if (res1.code == 200) {
			
	// 		ctx.rest(data)
	// 	} else {

			
	// 		ctx.response.body = {
	// 			code: 200,
	// 			data: res
	// 		}
	// 	}
	// })

	return router;
}
